package com.sanchunhui.psc.ui.fragment

import android.media.MediaPlayer
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.facebook.drawee.backends.pipeline.Fresco
import com.kotlin.message.data.protocol.Message
import com.sanchunhui.psc.R
import com.sanchunhui.psc.ui.adapter.AlarmsMessageAdapter
import com.sanchunhui.psc.utils.AlarmsObservable
import kotlinx.android.synthetic.main.fragment_alarms.*
import org.jetbrains.anko.find
import org.json.JSONObject
import java.util.*

/**
 * @Author zyx
 * @Date 2021/5/18-9:59
 * @Dscribe 报警消息
 */
class AlarmsFragment : Fragment(),Observer {

    lateinit var alarmsMessageAdapter : AlarmsMessageAdapter
    lateinit var recyclerViewAlarms : RecyclerView
    var mediaPlayer:MediaPlayer?=null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = View.inflate(activity, R.layout.fragment_alarms, null)
        recyclerViewAlarms = view.find<RecyclerView>(R.id.rv_alarms)
        recyclerViewAlarms.layoutManager = LinearLayoutManager(activity)
        alarmsMessageAdapter = AlarmsMessageAdapter(activity)
        recyclerViewAlarms.adapter = alarmsMessageAdapter
        mediaPlayer = MediaPlayer.create(activity, R.raw.arm_sound)
        Fresco.initialize(context)
        return view
    }

    init {
        AlarmsObservable.instance.addObserver(this)  //让观察者和被观察者建立绑定关系
    }

    val allList:ArrayList<Message> = ArrayList()

    override fun update(observer: Observable?, data: Any?) {

        //观察者的响应
        Log.e("alarms","观察者收到了消息内容:"+data)
        val jsonObj : JSONObject = JSONObject(data as String)
//        val pushId = jsonObj.getString("orderId")
        val pushTitle = jsonObj.getString("msgTitle")
        val pushContent = jsonObj.getString("msgContent")

        val messageBean = Message("",pushTitle,pushContent,"")

        allList.add(messageBean!!)

        if (allList.size > 0) {
            tv_alarms_empty.visibility = View.GONE
        } else {
            tv_alarms_empty.visibility = View.VISIBLE
        }

        alarmsMessageAdapter.setData(allList)

        //播放音乐
        mediaPlayer!!.start()
        mediaPlayer!!.prepareAsync()

    }
}